package com.chookss.home.other;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.adapter.NoticeListsAdapter;
import com.chookss.home.entity.NoticeListEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.components.SimpleImmersionFragment;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class NoticeBaseFragment extends SimpleImmersionFragment {

    public Activity mContext;
    Unbinder unbinder;
    @BindView(R.id.statusBar)
    View statusBar;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.title_back)
    LinearLayout title_back;


    @BindView(R.id.rvNotice)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout smrRf;
    private NoticeListsAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<NoticeListEntity> list = new ArrayList<>();
    private View emptyView;
    private TextView tvEmpty;//空布局;
    private int type = 0; //0一级页面没有返回1是activity要返回
    public NoticeBaseFragment() {

    }
    public NoticeBaseFragment(int type) {
        this.type = type;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_notice_list, container, false);
        unbinder = ButterKnife.bind(this, view);
        //注册接受
        EventBus.getDefault().register(this);
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        //顶部状态栏 处理
        NavigationTools.saveUseRecord(mContext,"1","01");
        if (type == 0) {
            int statusBarHeight = Utils.getStatusBarHeight(mContext);
            LinearLayout.LayoutParams topAllParams = (LinearLayout.LayoutParams) statusBar.getLayoutParams();
            topAllParams.height = statusBarHeight;
            statusBar.setLayoutParams(topAllParams);
            statusBar.setVisibility(View.VISIBLE);
            statusBar.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            title_back.setVisibility(View.GONE);
            tvTitle.getPaint().setFakeBoldText(true);
        } else {
            statusBar.setVisibility(View.GONE);
            title_back.setVisibility(View.VISIBLE);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new NoticeListsAdapter(R.layout.item_notice, mContext, list);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvEmpty = emptyView.findViewById(R.id.tvEmpty);
        tvEmpty.setText("暂无公告");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@io.reactivex.annotations.NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }
    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", "20");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<NoticeListEntity>>>() {
        }.getType(), null, Urls.getNoticeList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<NoticeListEntity>>() {
            @Override
            public void onSuccess(List<NoticeListEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if(!"13503825592".equals(new ShareUtils().getString(mContext, StaticClass.USERNAME,""))){
                    if (data != null && data.size() > 0) {
                        list.addAll(data);
                        adapter.notifyDataSetChanged();
                    } else {
                        isEnd = true;
                        if (list.size() == 0) {
                            adapter.setEmptyView(emptyView);
                        }
                    }
                }else{
                    for (int i = 0; i < data.size(); i++) {
                        if(!data.get(i).getNoticeTitle().contains("企小竹")){
                            list.add(data.get(i));
                        }
                    }
                    if ( data.size() > 0) {
                        adapter.notifyDataSetChanged();
                    } else {
                        isEnd = true;
                        if (list.size() == 0) {
                            adapter.setEmptyView(emptyView);
                        }
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.title_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                if(mContext!=null){
                    mContext.finish();
                }
                break;
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if("NoticeBaseFragment".equals(msg)){
                //刷新最近列表
                smrRf.autoRefresh();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initImmersionBar() {
        ImmersionBar.with(getActivity())
                .transparentStatusBar()  /*透明状态栏，不写默认透明色*/  /*状态栏字体是深色，不写默认为亮色*/
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.grey_3)  /*修改flyme OS状态栏字体颜色*/
                .keyboardEnable(false).navigationBarEnable(false)
                .init();
    }
}
